<template>
    <div class="container" style="border: 1px solid #ccc; margin-top: 10px">
        <!-- 工具栏 -->
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
        <!-- 编辑器 -->
        <Editor style="height:700px;overflow-y: hidden;font-size: 16px;" :defaultConfig="editorConfig" v-model="html"
            @onChange="onChange" @onCreated="onCreated" />
    </div>
</template>
  
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import OSS from 'ali-oss'
import Vue from 'vue'
import * as Constants from "@/constants/constants";
import ComponentApi from "@/api/components/component";
var ossClient = null
// 自定义校验图片
function customCheckImageFn(src, alt, url) {
    if (!src) {
        return
    }
    if (src.indexOf('http') !== 0) {
        return '图片网址必须以 http/https 开头'
    }
    return true
}

// 转换图片链接
function customParseImageSrc(src) {
    if (src.indexOf('http') !== 0) {
        return `http://${src}`
    }
    return src
}
// 上传到OSS
function uploadOSS(file, callback, dirname) {
    const fileName = file.name;
    // 避免文件名带有多个.
    let fileNameArr = fileName.split("\.");
    const fileType = fileNameArr[fileNameArr.length - 1];
    const newName = Vue.prototype.$Utils.mathRand19() + "." + fileType;
    const storeAs = Constants.OSS_WEB_URL +'rich-editor'+ '/' + newName;
    ossClient.put(storeAs, file).then(function (ret) {
        if (ret.res.statusCode === 200) {
            let url = ret.url.replace(Constants.OSS_URL, Constants.OSS_REAL_URL);
            callback({ url: url })
        } else {
            callback(0)
        }
    }).catch(err => {
        callback(0);
    });
}
export default {
    name: "RichEditor",
    components: { Editor, Toolbar },
    props:{
        htmlText:{
            type:String,
        },
        readOnly :{
            type:Boolean,
            default:false
        }
    },
    data() {
        return {
            editor: null,
            html:"",
            toolbarConfig: {

            },
            editorConfig: {
                readOnly :true,
                // scroll:false,
                placeholder: "请输入内容...",
                MENU_CONF: {
                    fontSize:{
                        // fontSizeList:[ 
                        // { name: '默认字体', value: '16px' },
                        // '12px',
                        // '16px',
                        // '40px'],
                    },
                    insertImage: {
                        onInsertedImage(imageNode) {
                            if (imageNode == null) return
                            const { src, alt, url, href } = imageNode
                            console.log('inserted image', src, alt, url, href)
                        },
                        checkImage: customCheckImageFn, // 也支持 async 函数
                        parseImageSrc: customParseImageSrc, // 也支持 async 函数
                    },
                    editImage: {
                        onUpdatedImage(imageNode) {
                            if (imageNode == null) return
                            const { src, alt, url } = imageNode
                            console.log('updated image', src, alt, url)
                        },
                        checkImage: customCheckImageFn, // 也支持 async 函数
                        parseImageSrc: customParseImageSrc, // 也支持 async 函数
                    },
                    uploadImage: {
                        async customUpload(file, insertFn) {
                            uploadOSS(file, (res) => {
                                if (res) {
                                    insertFn(res.url)
                                }
                            })

                        }
                    }
                },
            },
        };
    },
    watch:{
        htmlText(val){
            this.html = val
        },
        readOnly :{
            handler(val){
                this.editorConfig.readOnly  = val
            },
            immediate:true,
            
        },
    },
    methods: {
        init() {
            ComponentApi.uploadOss().then(res => {
                ossClient = new OSS({
                    region: Constants.OSS_REGION,
                    accessKeyId: res.data.accessKeyId,
                    accessKeySecret: res.data.accessKeySecret,
                    stsToken: res.data.securityToken,
                    bucket: Constants.OSS_BUCKET
                })
            })
        },
        onCreated(editor) {
            this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        },
        onChange(editor) {
            // onChange 时获取编辑器最新内容
           this.$emit("getHtmlText",editor.getHtml())
        },
    },
    mounted() {
        this.init()
    },
    beforeDestroy() {
        const editor = this.editor;
        if (editor == null) return;
        editor.destroy(); // 组件销毁时，及时销毁 editor ，重要！！！
    },
};
</script>
  
<style src="@wangeditor/editor/dist/css/style.css"></style>

<style>
    .container{
        z-index:9999;
        background-color: white !important;
    }
</style>
  